package com.edu.lxshpc.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.lxshpc.pojo.Music;
import com.edu.lxshpc.service.MusicService;
import com.edu.lxshpc.mapper.MusicMapper;
import com.edu.lxshpc.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.edu.lxshpc.utils.RedisStatic.EXPIRE;
import static com.edu.lxshpc.utils.RedisStatic.MUSIC_LIST_KEY;

/**
* @author Sanshan
* @description 针对表【music】的数据库操作Service实现
* @createDate 2023-11-13 17:22:19
*/
@Service
public class MusicServiceImpl extends ServiceImpl<MusicMapper, Music>
    implements MusicService{
    @Autowired
    private MusicMapper musicMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Override
    public Result getMusicList() {
        if (Boolean.TRUE.equals(stringRedisTemplate.hasKey(MUSIC_LIST_KEY))) {
            String json = stringRedisTemplate.opsForValue().get(MUSIC_LIST_KEY);
            List<Music> music = JSONUtil.toList(json, Music.class);
            return Result.success(music);
        }
        List<Music> musicList = musicMapper.selectList(new QueryWrapper<Music>());
        if (musicList == null || musicList.size() == 0) {
            return Result.fail("没有音乐");
        }
        String s = JSONUtil.toJsonStr(musicList);
        stringRedisTemplate.opsForValue().set(MUSIC_LIST_KEY, s,EXPIRE, TimeUnit.MINUTES);
        return Result.success(musicList);
    }
}




